package com.paiai.lslease.action.apphouse;

import com.paiai.lslease.auto.model.AppInvitation;
import com.paiai.lslease.auto.model.AppSysUser;
import com.paiai.lslease.base.BaseAction;
import com.paiai.lslease.service.apphouse.AppLockService;
import com.paiai.lslease.service.apphouse.AppLockTenantService;
import com.paiai.lslease.service.appinvite.AppInviteService;
import com.paiai.lslease.service.appuser.AppSysUserService;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Locale;

public class AppInviteAction extends BaseAction {

    private static final Logger logger = LoggerFactory.getLogger(AppInviteAction.class);

    private AppInviteService appInviteService;
    private AppLockService appLockService;
    private AppSysUserService appSysUserService;
    @Autowired
    private AppLockTenantService appLockTenantService;

    private String invitationId;
    private String operateUserId;
    private String loginUserId;
    private String landlordId;
    private String userMobile;
    private String lockId;
    private String sendInviteTime;
    private String rentingEndTime;

    public void setInvitationId(String invitationId) {
        this.invitationId = invitationId;
    }

    public void setAppInviteService(AppInviteService appInviteService) {
        this.appInviteService = appInviteService;
    }

    public void setOperateUserId(String operateUserId) {
        this.operateUserId = operateUserId;
    }

    public void setLoginUserId(String loginUserId) {
        this.loginUserId = loginUserId;
    }

    public void setLandlordId(String landlordId) {
        this.landlordId = landlordId;
    }

    public void setUserMobile(String userMobile) {
        this.userMobile = userMobile;
    }

    public void setLockId(String lockId) {
        this.lockId = lockId;
    }

    public void setSendInviteTime(String sendInviteTime) {
        this.sendInviteTime = sendInviteTime;
    }

    public void setRentingEndTime(String rentingEndTime) {
        this.rentingEndTime = rentingEndTime;
    }

    public void setAppLockService(AppLockService appLockService) {
        this.appLockService = appLockService;
    }

    @Override
    public void setAppSysUserService(AppSysUserService appSysUserService) {
        this.appSysUserService = appSysUserService;
    }

    @Override
    public String toString() {
        return "AppInviteAction{" +
                "appInviteService=" + appInviteService +
                ", appLockService=" + appLockService +
                ", appSysUserService=" + appSysUserService +
                ", invitationId='" + invitationId + '\'' +
                ", operateUserId='" + operateUserId + '\'' +
                ", landlordId='" + landlordId + '\'' +
                ", userMobile='" + userMobile + '\'' +
                ", lockId='" + lockId + '\'' +
                ", sendInviteTime='" + sendInviteTime + '\'' +
                ", rentingEndTime='" + rentingEndTime + '\'' +
                '}';
    }

    /**
     * 房东给用户发送租房邀请
     */
    public void sendRentingInvitation() {
        try {
            if (StringUtils.isEmpty(operateUserId)) {
                sendFailureMsg("操作的用户ID不能为空");
                return;
            }
            if (!StringUtils.isNumeric(operateUserId)) {
                sendFailureMsg("操作的用户ID格式错误");
                return;
            }
            if (!appSysUserService.userExist(Integer.parseInt(operateUserId))) {
                sendFailureMsg("操作的用户不存在");
                return;
            }
            if (StringUtils.isEmpty(landlordId)) {
                sendFailureMsg("房东ID不能为空");
                return;
            }
            if (!StringUtils.isNumeric(landlordId)) {
                sendFailureMsg("房东ID格式错误");
                return;
            }
            if (!appSysUserService.userBelongLandlord(Integer.parseInt(landlordId))) {
                sendFailureMsg("房东不存在");
                return;
            }
            if (StringUtils.isEmpty(userMobile)) {
                sendFailureMsg("被邀请的用户的手机号码不能为空");
            }
            if (!StringUtils.isNumeric(userMobile) || userMobile.length() != 11) {
                sendFailureMsg("被邀请的用户的手机号码格式错误");
            }
            if (StringUtils.isEmpty(lockId)) {
                sendFailureMsg("被邀请的用户入住的房间的设备ID不能为空");
                return;
            }
            //被邀请的用户可能未注册，因此不检验其是否已注册
            if (!StringUtils.isNumeric(lockId)) {
                sendFailureMsg("被邀请的用户入住的房间的设备ID格式错误");
                return;
            }
            if (!appLockService.lockExistById(Integer.parseInt(lockId))) {
                sendFailureMsg("被邀请的用户入住的房间的设备不存在");
                return;
            }
            //验证设备是否属于房东
            if (!appLockService.lockBelongUser(Integer.parseInt(lockId), Integer.parseInt(landlordId))) {
                sendFailureMsg("该设备不属于该房东，不能邀请");
                return;
            }
            if (appInviteService.existNotAcceptInvitation(Integer.parseInt(landlordId), userMobile, Integer.parseInt(lockId))) {
                sendFailureMsg("已邀请过该用户入住该房间，请该用户接受邀请");
                return;
            }
            Date sendRentingDate;
            if (StringUtils.isEmpty(sendInviteTime)) {
                sendRentingDate = new Date();
                sendRentingDate.setHours(0);
                sendRentingDate.setMinutes(0);
                sendRentingDate.setSeconds(0);
            } else {
                try {
                    sendRentingDate = new SimpleDateFormat("yyyy-MM-dd", Locale.CANADA).parse(sendInviteTime);
                } catch (Exception e) {
                    e.printStackTrace();
                    sendFailureMsg("开始入住的日期格式错误");
                    return;
                }
            }
            Date endRentingDate;
            if (StringUtils.isEmpty(rentingEndTime)) {
                sendFailureMsg("租住到期日期不能为空");
                return;
            }
            try {
                endRentingDate = new SimpleDateFormat("yyyy-MM-dd", Locale.CANADA).parse(rentingEndTime);
            } catch (Exception e) {
                e.printStackTrace();
                sendFailureMsg("租住到期的日期格式错误");
                return;
            }
            if (Long.parseLong(new SimpleDateFormat("yyyy-MM-dd", Locale.CANADA).format(endRentingDate).replace("-", "")) <= Long.parseLong(new SimpleDateFormat("yyyy-MM-dd", Locale.CANADA).format(new Date()).replace("-", ""))) {
                sendFailureMsg("租住结束日期必须大于当前日期");
                return;
            }
            if (Long.parseLong(new SimpleDateFormat("yyyy-MM-dd", Locale.CANADA).format(endRentingDate).replace("-", "")) <= Long.parseLong(new SimpleDateFormat("yyyy-MM-dd", Locale.CANADA).format(sendRentingDate).replace("-", ""))) {
                sendFailureMsg("租住结束日期必须大于租住开始日期");
                return;
            }
            if (appLockTenantService.userHasLock(userMobile, Integer.parseInt(lockId))) {//用户已入住该房间
                //检查租客是否到期
                AppSysUser appSysUser = appSysUserService.getAppSysUserInfoByMobile(userMobile);
                if (appSysUser == null) {
                    sendFailureMsg("系统异常");
                    return;
                }
                if (!appLockTenantService.tenantExpired(appSysUser.getId(), Integer.parseInt(lockId))) {
                    logger.info("用户已入住该房间，并且房租未到期，不需再次邀请");
                    sendFailureMsg("用户已入住该房间，并且房租未到期，不需再次邀请");
                    return;
                }
                logger.info("用户已入住该房间，并且房租到期，可以再次邀请");
            }
            AppInvitation appInvitationToInsert = new AppInvitation();
            appInvitationToInsert.setLandlordId(Integer.valueOf(landlordId));
            appInvitationToInsert.setUserMobile(userMobile);
            appInvitationToInsert.setLockId(Integer.valueOf(lockId));
            appInvitationToInsert.setSendInviteTime(sendRentingDate);
            appInvitationToInsert.setRentingEndTime(endRentingDate);
            appInvitationToInsert.setState(1);
            appInvitationToInsert.setItem1("1");
            appInvitationToInsert.setInsertTime(new Date());
            appInvitationToInsert.setUpdateTime(new Date());
            AppInvitation appInvitation = appInviteService.sendRentingInvitation(appInvitationToInsert);
            if (appInvitation == null) {
                sendFailureMsg("发送租房邀请失败");
                return;
            }
            sendSuccesseMsg(appInvitation, "发送租房邀请成功");
        } catch (Exception e) {
            e.printStackTrace();
            sendFailureMsg("发送租房邀请失败");
        }
    }

    /**
     * 用户查询自己是否有新的租房邀请
     */
    public void selectUserRentingInvitationList() {
        try {
            if (StringUtils.isEmpty(operateUserId)) {
                sendFailureMsg("操作的用户ID不能为空");
                return;
            }
            if (!StringUtils.isNumeric(operateUserId)) {
                sendFailureMsg("操作的用户ID格式错误");
                return;
            }
            if (!appSysUserService.userExist(Integer.parseInt(operateUserId))) {
                sendFailureMsg("操作的用户不存在");
                return;
            }
            if (StringUtils.isEmpty(userMobile)) {
                sendFailureMsg("被邀请的用户的手机号码不能为空");
                return;
            }
            if (!StringUtils.isNumeric(userMobile) || userMobile.length() != 11) {
                sendFailureMsg("被邀请的用户的手机号码格式错误");
                return;
            }
            if (appSysUserService.getAppSysUserInfoByMobile(userMobile) == null) {
                sendFailureMsg("被邀请的用户不存在");
                return;
            }
            sendSuccesseMsg(appInviteService.selectUserRentingInvitationList(userMobile), "查询租房邀请列表成功");
        } catch (Exception e) {
            e.printStackTrace();
            sendFailureMsg("查询租房邀请列表失败");
        }
    }

    /**
     * 租客接受房东的租房邀请，确认入住
     */
    public void confirmRentingInvitation() {
        try {
            if (StringUtils.isEmpty(operateUserId)) {
                sendFailureMsg("操作的用户ID不能为空");
                return;
            }
            if (!StringUtils.isNumeric(operateUserId)) {
                sendFailureMsg("操作的用户ID格式错误");
                return;
            }
            if (!appSysUserService.userExist(Integer.parseInt(operateUserId))) {
                sendFailureMsg("操作的用户不存在");
                return;
            }
            if (StringUtils.isEmpty(invitationId)) {
                sendFailureMsg("邀请记录ID不能为空");
                return;
            }
            if (!StringUtils.isNumeric(invitationId)) {
                sendFailureMsg("邀请记录ID格式错误");
                return;
            }
            if (StringUtils.isEmpty(userMobile)) {
                sendFailureMsg("被邀请的用户的手机号码不能为空");
            }
            if (!StringUtils.isNumeric(userMobile) || userMobile.length() != 11) {
                sendFailureMsg("被邀请的用户的手机号码格式错误");
            }
            AppInvitation appInvitationToUpdate = appInviteService.selectSingleInvitation(Integer.parseInt(invitationId));
            if (appInvitationToUpdate == null) {
                sendFailureMsg("不存在该邀请");
                return;
            }
            if (!userMobile.equalsIgnoreCase(appInvitationToUpdate.getUserMobile() + "")) {
                logger.error("接受租房邀请的用户手机号码" + userMobile + "与房东邀请的用户的手机号码" + appInvitationToUpdate.getUserMobile() + "不一致");
                sendFailureMsg("接受租房邀请的用户手机号码与房东邀请的用户的手机号码不一致");
                return;
            }
            appInvitationToUpdate.setConfirmInviteTime(new Date());
            appInvitationToUpdate.setState(2);
            appInvitationToUpdate.setUpdateTime(new Date());
            if (!appInviteService.confirmRentingInvitationByPrimaryId(appInvitationToUpdate)) {
                sendFailureMsg("用户接受租房邀请失败");
                return;
            }
            sendSuccesseMsg("用户接受租房邀请成功");
        } catch (Exception e) {
            e.printStackTrace();
            sendFailureMsg("用户接受租房邀请失败");
        }
    }

    /**
     * 用户拒绝租房邀请
     */
    public void refuseRentingInvitation() {
        try {
            if (StringUtils.isEmpty(loginUserId)) {
                sendFailureMsg("登录的用户ID不能为空");
                return;
            }
            if (!StringUtils.isNumeric(loginUserId)) {
                sendFailureMsg("登录的用户ID格式错误");
                return;
            }
            if (!appSysUserService.userExist(Integer.parseInt(loginUserId))) {
                sendFailureMsg("登录的用户不存在");
                return;
            }
            if (StringUtils.isEmpty(invitationId)) {
                sendFailureMsg("邀请记录ID不能为空");
                return;
            }
            if (!StringUtils.isNumeric(invitationId)) {
                sendFailureMsg("邀请记录ID格式错误");
                return;
            }
            AppInvitation appInvitation = appInviteService.selectSingleInvitation(Integer.parseInt(invitationId));
            if (appInvitation == null) {
                sendFailureMsg("邀请记录不存在");
                return;
            }
            if (appInvitation.getState() != 1) {
                sendFailureMsg("没有可拒绝的邀请");
                return;
            }
            appInvitation.setItem1("-1");
            appInvitation.setState(2);
            appInvitation.setUpdateTime(new Date());
            AppInvitation appInvitation_ = appInviteService.updateRentingInvitation(appInvitation);
            if (appInvitation_ == null) {
                sendFailureMsg("用户拒绝租房邀请失败");
                return;
            }
            sendSuccesseMsg(appInvitation_, "用户拒绝租房邀请成功");
        } catch (Exception e) {
            e.printStackTrace();
            sendFailureMsg("用户拒绝租房邀请失败");
        }
    }

    /**
     * 根据邀请ID查询租房邀请信息
     */
    public void selectUserRentingInvitationById() {
        try {
            logger.info("根据邀请ID查询租房邀请信息------\n" + this.toString());
            if (StringUtils.isEmpty(operateUserId)) {
                sendFailureMsg("操作的用户ID不能为空");
                return;
            }
            if (!StringUtils.isNumeric(operateUserId)) {
                sendFailureMsg("操作的用户ID格式错误");
                return;
            }
            if (!appSysUserService.userExist(Integer.parseInt(operateUserId))) {
                sendFailureMsg("操作的用户不存在");
                return;
            }
            if (StringUtils.isEmpty(invitationId)) {
                sendFailureMsg("邀请记录ID不能为空");
                return;
            }
            if (!StringUtils.isNumeric(invitationId)) {
                sendFailureMsg("邀请记录ID格式错误");
                return;
            }
            AppInvitation appInvitation = appInviteService.selectSingleInvitation(Integer.parseInt(invitationId));
            if (appInvitation == null) {
                sendFailureMsg("邀请不存在，请检查邀请记录ID");
                return;
            }
            sendSuccesseMsg(appInvitation, "根据邀请ID查询租房邀请信息成功");
        } catch (Exception e) {
            e.printStackTrace();
            sendFailureMsg("根据邀请ID查询租房邀请信息失败");
        }
    }
}
